using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Collections.Specialized;

namespace Widgetsphere.WebUtils
{
	public class URLocationHelper
	{
		public const string IMAGE_UPLOAD_DIR = @"images\uploaded\";
		public const string IMAGE_UPLOAD_URL = "~/images/uploaded/";
		public const string DEFAULT_IMAGE = "default.gif";

		private URLocationHelper() { }

		public static bool IsSecureURL(HttpRequest request)
		{
			return IsSecureURL(request.Url.AbsoluteUri);
		}

		private static string SecurePrefix
		{
			get { return "https://"; }
		}

		public static bool IsSecureURL(string url)
		{
			return url.ToLower().StartsWith(SecurePrefix);
		}

		public static string EnsureSecuredURL(HttpRequest request)
		{
			return EnsureSecuredURL(request.Url.AbsoluteUri);
		}

		public static string EnsureSecuredURL(string url)
		{
			if (url.ToLower().StartsWith("http://"))
			{
				url = SecurePrefix + url.Substring(7, url.Length - 7);
			}
			else if (url.ToLower().StartsWith(SecurePrefix))
			{
				//Do Nothing
			}
			else
			{
				throw new Exception("Unrecognized URL!");
			}

			return url;

		}

		public static string EnsureUnSecuredURL(string url)
		{
			if (url.ToLower().StartsWith(SecurePrefix))
			{
				url = "http://" + url.Substring(8, url.Length - 8);
			}
			else if (url.ToLower().StartsWith("http://"))
			{
				//Do Nothing
			}
			else
			{
				throw new Exception("Unrecognized URL!");
			}

			return url;

		}

		public static string FormatSEOURL(string url)
		{
			var retval = "";
			if (url != null)
			{
				retval = url.ToLower().Replace(" ", "-");
				retval = retval.Replace("/", "-");
				retval = retval.Replace("'", "");
				retval = retval.Replace(",", "");
				retval = retval.Replace("&", "");
				retval = retval.Replace("--", "-");
			}
			return retval;
		}

		public static NameValueCollection GetQueryValues(string url)
		{
			var retval = new NameValueCollection();

			var arr = url.Split('?');
			url = arr[arr.Length - 1];
			url = url.Replace("?", "");
			arr = url.Split('&');
			foreach (var text in arr)
			{
				var arr2 = text.Split('=');
				if (arr2.Length == 2)
				{
					if (retval[arr2[0]] == null)
						retval.Add(arr2[0], arr2[1]);
					else
						retval[arr2[0]] = arr2[1];
				}
			}

			return retval;
		}

	}
}
